/*
 * DA06.c
 *
 * Created: 4/16/2014 5:13:46 PM
 *  Author: mummm2
 */ 

/*
Avcc = 5v
Aref = 10uF
PinC5 is adc pin
PORTB0-3 is output to stepper motor
*/


#define F_CPU 8000000UL

#include <avr/io.h>
#include <util/delay.h>

void Delay(int);

int main(void)
{
	DDRB = 0xff;	//PORTB0-3 is output to stepper motor
	
	int speed=50;	//initial delay for motor
	double curr = 0;//saves the current value from analog in
	
	//data will be L-Justified, PC5 for analog reading, 5V external ref with 10uf cap
	ADMUX = (0<<REFS1) | (1<<REFS0) | (1<<ADLAR) | (0<<MUX3) | (1<<MUX2) | (0<<MUX1) | (1<<MUX0);
	//make ADC enable and select ck/128
	ADCSRA = (1<<ADEN) | (0<<ADSC) | (0<<ADATE) | (0<<ADIF) | (0<<ADIE) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
	
	//initialize value of ADC
	ADCSRA |= (1<<ADSC);			//Start Conversion
	while((ADCSRA&(1<<ADIF))==0);	//wait for end of conversion
	curr = ADC;
	
	while(1)
	{
		
		ADCSRA |= (1<<ADSC);			//Start Conversion
		while((ADCSRA&(1<<ADIF))==0);	//wait for end of conversion
		
		if(ADC > curr)		//if the new ADC value is greater than the current one
		speed += 10;		//decrease the delay, which increases the speed
		else if (ADC < curr)//if the new ADC value is less than the current one
		speed -= 10;		//increase the delay, which decreases the speed
		
		curr = ADC;			//set the new ADC value as the current value
		
		if(speed < 10)	 	//if the delay is less than 10, the motor will not spin.
		speed = 10;
		if(speed > 500)		//set a max delay so the motor will continue to spin
		speed = 500;
		
		//actual rotation of the motor. 
		PORTB = 0x11;		
		Delay(speed);	//send the delay amount to a separate function
		PORTB = 0x22;
		Delay(speed);
		PORTB = 0x44;
		Delay(speed);
		PORTB = 0x88;
		Delay(speed);
		
	}
}

//Loop to delay since _delay_ms does not accept variables.
void Delay(int time) {
	while(time--){
		_delay_ms(1);
	}
}